package com.sld.concrete.monitor.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.sld.concrete.algorithm.mapper.RecDevCalculateMapper;
import com.sld.concrete.monitor.dto.*;
import com.sld.concrete.monitor.service.IConcreteMonitorService;
import com.sld.concrete.vehicle.domain.InfoVehicle;
import com.sld.concrete.vehicle.dto.RecDevWorkSequenceStatDTO;
import com.sld.concrete.vehicle.mapper.InfoVehicleMapper;
import com.sld.concrete.vehicle.mapper.RecDevWorkSequenceMapper;
import com.sld.concrete.vehicle.service.IInfoVehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述:
 *
 * @Author tanli
 * @create 2022-04-01 10:41
 */
@Slf4j
@Service
public class ConcreteMonitorServiceImpl implements IConcreteMonitorService {

    @Resource
    RecDevCalculateMapper recDevCalculateMapper;
    @Resource
    IInfoVehicleService vehicleService;
    @Resource
    RecDevWorkSequenceMapper recDevWorkSequenceMapper;
    @Resource
    InfoVehicleMapper infoVehicleMapper;

    @Override
    public Map<String, Object> queryIndexData() {
        Map<String, Object> returnMap = new HashMap<>();
        //1. 查询当前用户权限范围内的所有车辆。（plateNo, deptId, deptName）
        List<InfoVehicle> vehicles = vehicleService.selectInfoVehicleList(new InfoVehicle());
        String plateNos = "";
        for(int i=0;i<vehicles.size();i++){
            plateNos = "'"+vehicles.get(i).getPlateNo()+"',";
        }
        //去掉末尾的“,”
        plateNos = plateNos.substring(0,plateNos.length()-1);

        //2. 查询这些车近7日运输任务次数。当天记录数、当天完成任务、当天进行中。（rec_dev_work_sequence）
        Map<String, Object> taskMap = new HashMap<>();
        //当天
        String todayBeginTime = DateUtils.getDate()+" 00:00:00";
        String todayEndTime = DateUtils.getDate()+" 23:59:59";
        RecDevWorkSequenceStatDTO todayStat = recDevWorkSequenceMapper.queryTaskStat(plateNos,todayBeginTime,todayEndTime);
        taskMap.put("todayCount",todayStat.getCount());
        taskMap.put("todayOngoing",todayStat.getOnGoing());
        taskMap.put("todayComplete",todayStat.getComplete());
        //最近7天（包含今天）
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,-6);
        Date beginDate = cal.getTime();
        String recentBeginTime = DateUtils.parseDateToStr("yyyy-MM-dd",beginDate)+" 00:00:00";
        String recentEndTime = DateUtils.parseDateToStr("yyyy-MM-dd",new Date())+" 23:59:59";
        int recentCount = recDevWorkSequenceMapper.queryTaskCount(plateNos,recentBeginTime,recentEndTime);
        taskMap.put("recent7Days",recentCount);
        returnMap.put("taskOverview",taskMap);

        //3. 查询这些车所有没有registerId的记录。（rec_dev_work_sequence registerId字段为null）
        List<UnRegisterWorkSequenceDTO> unRegistList = recDevWorkSequenceMapper.queryUnRegister(plateNos);
        returnMap.put("unregistered",unRegistList);

        //4. 查询这些车最新记录，就是每辆车最后一个记录。 （我感觉过滤掉已完成时间超过24小时的比较好）
        //根据车牌，查询全部部门统计信息
        List<DeptVehicleSequenceDTO> totalList = recDevWorkSequenceMapper.queryDeptByPlateNos(plateNos);
        //根据车牌，查询最近24小时有任务的统计信息
        Date endTime = new Date();
        Date beginTime = new Date(endTime.getTime()-24*60*60*1000);
        String beginTimeStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",beginTime);
        String endTimeStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",endTime);
        List<DeptVehicleSequenceDTO> hasTaskList = recDevWorkSequenceMapper.queryDeptHasSequenceTaskWithinTime(plateNos,beginTimeStr,endTimeStr);
        Map<String,DeptVehicleSequenceDTO> hasTaskMap = new HashMap<>();
        for(DeptVehicleSequenceDTO temp:hasTaskList){
            hasTaskMap.put(temp.getDeptId(),temp);
        }
        //最近24小时，没有任务的部门信息
        List<DeptVehicleSequenceDTO> notHasTaskList = new ArrayList<>();
        for(DeptVehicleSequenceDTO temp:totalList){
            if(hasTaskMap.get(temp.getDeptId())==null){
                notHasTaskList.add(temp);
            }
        }

        //已完成时间在24小时内的，先显示
        List<DeptVehicleSequenceDTO> totalTaskList = new ArrayList<>();

        for(DeptVehicleSequenceDTO hasTaskDTO:hasTaskList){
            String deptId = hasTaskDTO.getDeptId();
            //查询此部门下的车牌（且在当前用户车牌权限plateNos范围内）
            List<InfoVehicle> plateList = infoVehicleMapper.queryInfoVehicleByDeptPlateNos(Integer.parseInt(deptId),plateNos);
            List<SequenceTaskDTO> deptTaskList = new ArrayList<>();
            for(InfoVehicle plateTemp:plateList){
                //查询此车牌的任务信息（24小时内时间最晚的sequence信息）
                RecDevWorkSequenceExtend vo = recDevWorkSequenceMapper.queryLastWordStatDataByPlateNo(plateTemp.getPlateNo(),beginTimeStr,endTimeStr);
                if(vo != null){
                    SequenceTaskDTO dto = new SequenceTaskDTO();
                    dto.setNo(vo.getId());
                    dto.setPlateNo(vo.getPlateNo());
                    dto.setWorkSequence(vo.getWorkSequence());
                    dto.setStartTime(vo.getStartTime());
                    dto.setEndTime(vo.getEndTime());
                    if(vo.getStartTime()!=null){
                        //如果结束时间为空，则赋值当前系统时间
                        Date endTimeD = vo.getEndTime()==null?new Date():vo.getEndTime();
                        dto.setDuration(DateUtils.getDuration(endTimeD,vo.getStartTime()));
                    }
                    dto.setWorkDate(DateUtils.parseDateToStr("yyyy-MM-dd",vo.getWorkDate()));
                    //标定
                    CalibrationDTO stand = new CalibrationDTO();
                    stand.setPressure(vo.getStandPressure());
                    stand.setSpeed(vo.getStandSpeed());
                    stand.setTemperature(vo.getStandTemperature());
                    stand.setHumidity(vo.getStandHumidity());
                    dto.setCalibration(stand);
                    //计算结果
                    CalculateDTO calc = new CalculateDTO();
                    calc.setPressure(vo.getCalcPressure());
                    calc.setSpeed(vo.getCalcSpeed());
                    calc.setTemperature(vo.getCalcTemperature());
                    calc.setHumidity(vo.getCalcHumidity());
                    calc.setCalcResult(vo.getCalcResult());
                    calc.setCalcTime(vo.getCalcTime());
                    dto.setCalculate(calc);
                    deptTaskList.add(dto);
                }
            }
            hasTaskDTO.setTasks(deptTaskList);
        }
        totalTaskList.addAll(hasTaskList);
        //超过24小时的，放在后面显示（task为空）
        totalTaskList.addAll(notHasTaskList);

        returnMap.put("tasks",totalTaskList);
        return returnMap;
    }
}
